import os

def _urlify(f):
    f = f.replace('C:\\', 'C:/')
    f = f.replace('\\', '/')
    f = 'file://' + f
    return f


def target_name(source_file_path, target_type):
    """Returns the target file name from the source svg file path."""
    # Fixme: Move elsewhere
    ext = '.' + target_type
    basename = os.path.basename(source_file_path)
    return basename.replace('.svgz', ext).replace('.svg', ext)


def svg_to_test_suite_png(svg_root, filename):
    """Returns the target png file name from the source svg file path."""
    filename = os.path.basename(filename).replace('.svgz', '.png').replace('.svg', '.png')
    return os.path.join(svg_root, 'png', filename)


def write_html_index(target_dir, target_type, svg_file_paths,
                     svg_test_suite_root):
    filename = os.path.join(target_dir, 'index.html')
    with open(filename, 'w') as html:
        html.write('<html><head></head><body>')
        html.write('Generated by %s.<p>' % os.path.basename(__file__))
        html.write('<table border="0">')
        for f in svg_file_paths:
            png_target = os.path.join(target_dir, target_name(f, target_type))
            base = os.path.basename(f)
            html.write('<tr><td>%s</td><td><center>Faint</center><br><img src="%s" width="480" height="360"/></td><td><center>Test suite PNG</center><br><img src="%s" width="480" height="360"/></td></tr>' % (base, _urlify(png_target), _urlify(svg_to_test_suite_png(svg_test_suite_root, f))))
        html.write('</table></body></html>')
